import { getHotRecommendAPI } from '@/services/hot'
import type { SubTypeItem, UrlItem } from '@/types/hot'
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'

const useHotHooks = () => {
  // 热门推荐页 标题和url
  const urlMap: UrlItem[] = [
    { type: '1', title: '特惠推荐', url: '/hot/preference' },
    { type: '2', title: '爆款推荐', url: '/hot/inVogue' },
    { type: '3', title: '一站买全', url: '/hot/oneStop' },
    { type: '4', title: '新鲜好物', url: '/hot/new' },
  ]

  let currentObj: UrlItem | null = null

  // 推荐封面图
  const bannerPicture = ref('')

  // 推荐选项
  const subTypes = ref<(SubTypeItem & { finish?: boolean })[]>([])

  // 高亮的下标
  const activeIndex = ref(0)

  // 获取热门推荐数据
  const getHotRecommendData = async (url: string) => {
    // 获取热门推荐数据
    const res = await getHotRecommendAPI(url, {
      page: 1,
      pageSize: 10,
    })
    bannerPicture.value = res.result.bannerPicture
    subTypes.value = res.result.subTypes
  }

  // 初始化数据获取展示数据并设置页面title
  const initData = (type: string) => {
    currentObj = urlMap.find((item) => item.type === type) as UrlItem
    uni.setNavigationBarTitle({ title: currentObj!.title })
    getHotRecommendData(currentObj!.url)
  }

  // 滚动触底
  const onScrolltolower = async () => {
    // 获取当前选项
    const currsubTypes = subTypes.value[activeIndex.value]
    // 分页条件
    if (currsubTypes.goodsItems.page < currsubTypes.goodsItems.pages) {
      // 当前页码累加
      currsubTypes.goodsItems.page++
    } else {
      // 标记已结束
      currsubTypes.finish = true
      // 退出并轻提示
      return uni.showToast({ icon: 'none', title: '没有更多数据了~' })
    }

    // 调用API传参
    const res = await getHotRecommendAPI(currentObj!.url, {
      subType: currsubTypes.id,
      page: currsubTypes.goodsItems.page,
      pageSize: currsubTypes.goodsItems.pageSize,
    })
    // 新的列表选项
    const newsubTypes = res.result.subTypes[activeIndex.value]
    // 数组追加
    currsubTypes.goodsItems.items.push(...newsubTypes.goodsItems.items)
  }

  // 页面加载
  onLoad((option) => {
    initData(option!.type)
  })

  return {
    bannerPicture,
    subTypes,
    activeIndex,
    onScrolltolower,
  }
}

export default useHotHooks
